/*
 * CodeGenerator.java
 * Created on __DATE__, __TIME__
 */
package com.code.generate;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;

import com.alibaba.fastjson.JSON;
import com.code.generate.enums.ControlType;
import com.code.generate.enums.FieldType;

/**
 * @author richard
 */
public class CodeGenerator extends javax.swing.JFrame {
    private static final int DATABASE_TYPE_DB2 = 0;
    private static final int DATABASE_TYPE_SQL_SERVER = 3;
    private static final int DATABASE_TYPE_ORACLE = 2;
    private static final int DATABASE_TYPE_MYSQL = 1;
    private static final long serialVersionUID = 1L;

    /**
     * Creates new form CodeGenerator
     */
    public CodeGenerator() {
        initComponents();
        int w = (Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth()) / 2;
        int h = (Toolkit.getDefaultToolkit().getScreenSize().height - this.getHeight()) / 2;
        this.setLocation(w, h);
        loadConfigFile();
        if (this.templatePath.getText().length() > 0) {
            ComboBoxModel dvbm = initTemplateList();
            this.templateList.setModel(dvbm);
        }
        this.filed_config_jTabbedPane1.setSelectedIndex(0);
        readVariables();
    }

    //
    // GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        data_source_setter_dialog_window = new javax.swing.JDialog();
        database_type_combo_box = new javax.swing.JComboBox();
        database_type_jLabel1 = new javax.swing.JLabel();
        database_driven_jLabel2 = new javax.swing.JLabel();
        database_url_jLabel3 = new javax.swing.JLabel();
        database_username_jLabel4 = new javax.swing.JLabel();
        database_password_jLabel5 = new javax.swing.JLabel();
        database_schema_jLabel6 = new javax.swing.JLabel();
        database_driver_text_field = new javax.swing.JTextField();
        database_url_text_field = new javax.swing.JTextField();
        database_username_text_field = new javax.swing.JTextField();
        database_password_text_field = new javax.swing.JTextField();
        database_schema_text_field = new javax.swing.JTextField();
        save_database_config_button = new javax.swing.JButton();
        reset_datebase_config = new javax.swing.JButton();
        help_about = new javax.swing.JDialog();
        help_about_jLabel6 = new javax.swing.JLabel();
        help_about_jLabel7 = new javax.swing.JLabel();
        help_about_jLabel8 = new javax.swing.JLabel();
        jfc = new javax.swing.JFileChooser();
        model_root_path_jLabel9 = new javax.swing.JLabel();
        templatePath = new javax.swing.JTextField();
        changeTemplatePath = new javax.swing.JButton();
        create_root_path_jLabel10 = new javax.swing.JLabel();
        generatePath = new javax.swing.JTextField();
        changeGeneratePath = new javax.swing.JButton();
        filed_config_jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        variablesTable = new javax.swing.JTable();
        filed_config_jScrollPane2 = new javax.swing.JScrollPane();
        fieldTable = new javax.swing.JTable();
        create_code_jButton3 = new javax.swing.JButton();
        create_template_jLabel11 = new javax.swing.JLabel();
        templateList = new javax.swing.JComboBox();
        read_variables_Button = new javax.swing.JButton();
        read_fields_from_table_Button = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        top_file_menu = new javax.swing.JMenu();
        top_file_open_MenuItem = new javax.swing.JMenuItem();
        top_file_database_setter_menu_Item = new javax.swing.JMenuItem();
        model_path_setting_Item = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        generate_path_setting_Item = new javax.swing.JMenuItem();
        generate_code_Item = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();
        menuBar1 = new javax.swing.JMenuBar();
        fileMenu1 = new javax.swing.JMenu();
        openMenuItem1 = new javax.swing.JMenuItem();
        dataBaseItem1 = new javax.swing.JMenuItem();
        modelPathItem1 = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        generatePathItem1 = new javax.swing.JMenuItem();
        generateItem1 = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        exitMenuItem1 = new javax.swing.JMenuItem();
        editMenu1 = new javax.swing.JMenu();
        cutMenuItem1 = new javax.swing.JMenuItem();
        copyMenuItem1 = new javax.swing.JMenuItem();
        pasteMenuItem1 = new javax.swing.JMenuItem();
        helpMenu1 = new javax.swing.JMenu();
        contentsMenuItem1 = new javax.swing.JMenuItem();
        aboutMenuItem1 = new javax.swing.JMenuItem();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        menuBar2 = new javax.swing.JMenuBar();
        fileMenu2 = new javax.swing.JMenu();
        openMenuItem2 = new javax.swing.JMenuItem();
        dataBaseItem2 = new javax.swing.JMenuItem();
        modelPathItem2 = new javax.swing.JMenuItem();
        jSeparator5 = new javax.swing.JSeparator();
        generatePathItem2 = new javax.swing.JMenuItem();
        generateItem2 = new javax.swing.JMenuItem();
        jSeparator6 = new javax.swing.JSeparator();
        exitMenuItem2 = new javax.swing.JMenuItem();
        editMenu2 = new javax.swing.JMenu();
        cutMenuItem2 = new javax.swing.JMenuItem();
        copyMenuItem2 = new javax.swing.JMenuItem();
        pasteMenuItem2 = new javax.swing.JMenuItem();
        helpMenu2 = new javax.swing.JMenu();
        contentsMenuItem2 = new javax.swing.JMenuItem();
        aboutMenuItem2 = new javax.swing.JMenuItem();
        data_source_setter_dialog_window.setTitle("数据源设置");
        data_source_setter_dialog_window.setMinimumSize(new java.awt.Dimension(380, 300));
        data_source_setter_dialog_window.setModal(true);
        data_source_setter_dialog_window.setResizable(false);
        database_type_combo_box.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"DB2", "MYSQL", "ORACLE", "SQL SERVER"}));
        database_type_combo_box.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                database_type_combo_box_ActionPerformed(evt);
            }
        });
        database_type_jLabel1.setText("数据库类型：");
        database_driven_jLabel2.setText("数据库驱动：");
        database_url_jLabel3.setText("数据连接URL：");
        database_username_jLabel4.setText("用户名：");
        database_password_jLabel5.setText("密码：");
        database_schema_jLabel6.setText("数据库：");
        save_database_config_button.setText("保存");
        save_database_config_button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveDataBaseActionPerformed(evt);
            }
        });
        reset_datebase_config.setText("重置");
        javax.swing.GroupLayout dataSetterLayout = new javax.swing.GroupLayout(data_source_setter_dialog_window.getContentPane());
        data_source_setter_dialog_window.getContentPane().setLayout(dataSetterLayout);
        dataSetterLayout.setHorizontalGroup(dataSetterLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(dataSetterLayout.createSequentialGroup().addGap(98, 98, 98).addComponent(save_database_config_button).addGap(57, 57, 57).addComponent(reset_datebase_config).addContainerGap(
                        117,
                        Short.MAX_VALUE))
                .addGroup(
                        dataSetterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                                dataSetterLayout
                                        .createSequentialGroup()
                                        .addGap(20, 20, 20)
                                        .addGroup(
                                                dataSetterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(database_driven_jLabel2)
                                                        .addComponent(database_type_jLabel1)
                                                        .addComponent(database_url_jLabel3)
                                                        .addComponent(database_username_jLabel4)
                                                        .addComponent(database_password_jLabel5)
                                                        .addComponent(database_schema_jLabel6)
                                        )
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(
                                                dataSetterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(database_password_text_field, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                                                        .addComponent(database_username_text_field, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                                                        .addComponent(database_url_text_field, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                                                        .addComponent(database_driver_text_field, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                                                        .addComponent(database_schema_text_field, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                                                        .addComponent(database_type_combo_box, 0, 264, Short.MAX_VALUE))
                                        .addGap(20, 20, 20))));
        dataSetterLayout.setVerticalGroup(dataSetterLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        javax.swing.GroupLayout.Alignment.TRAILING,
                        dataSetterLayout.createSequentialGroup().addContainerGap(168, Short.MAX_VALUE)
                                .addGroup(
                                        dataSetterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(save_database_config_button).addComponent(reset_datebase_config))
                                .addGap(19, 19, 19))
                .addGroup(
                        dataSetterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(
                                        dataSetterLayout
                                                .createSequentialGroup()
                                                .addGap(24, 24, 24)
                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_type_combo_box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(database_type_jLabel1))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_driven_jLabel2)
                                                                .addComponent(database_driver_text_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_url_jLabel3)
                                                                .addComponent(database_url_text_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_schema_jLabel6)
                                                                .addComponent(database_schema_text_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_username_jLabel4)
                                                                .addComponent(database_username_text_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                                                .addGroup(
                                                        dataSetterLayout
                                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(database_password_jLabel5)
                                                                .addComponent(database_password_text_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addContainerGap(57, Short.MAX_VALUE)

                                )));
        data_source_setter_dialog_window.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - data_source_setter_dialog_window.getWidth()) / 2,
                (Toolkit.getDefaultToolkit().getScreenSize().height - data_source_setter_dialog_window.getHeight()) / 2);
        initHelpAbout();
        model_root_path_jLabel9.setText("模板根路径：");
        templatePath.setEditable(true);
        changeTemplatePath.setText("...");
        changeTemplatePath.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeTemplatePathActionPerformed(evt);
            }
        });
        create_root_path_jLabel10.setText("生成跟路径：");
        generatePath.setEditable(true);
        changeGeneratePath.setText("...");
        changeGeneratePath.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeGeneratePathActionPerformed(evt);
            }
        });
        variablesTable.setAutoCreateRowSorter(true);
        variablesTable.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{}, new String[]{"序号", "变量名", "变量值"}) {
            boolean[] canEdit = new boolean[]{false, false, true};

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        variablesTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(variablesTable);
        variableManager = new TableManager(variablesTable);
        filed_config_jTabbedPane1.addTab("对应名称", jScrollPane1);
        filed_config_jScrollPane2.setAutoscrolls(true);
        fieldTable.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{}, new String[]{"序号", "数据库字段", "数据库类型", "属性名", "中文名", "字段类型", "数据长度", "控件类型", "查询条件", "列表显示", "编辑页面显示", "是否主键",
                "是否必填", "是否唯一"}) {
            Class[] types = new Class[]{java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class,
                    java.lang.Integer.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class,
                    java.lang.Boolean.class};
            boolean[] canEdit = new boolean[]{false, true, true, true, true, true, true, true, true, true, true, true, true, true};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        fieldTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        filed_config_jScrollPane2.setViewportView(fieldTable);
        fieldManager = new TableManager(fieldTable);
        initTableColumn();
        filed_config_jTabbedPane1.addTab("字段配置", filed_config_jScrollPane2);
        create_code_jButton3.setText("生成代码");
        create_code_jButton3.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                create_code_jButton3ActionPerformed(evt);
            }
        });
        create_template_jLabel11.setText("生成模板：");
        templateList.setModel(initTemplateList());
        templateList.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                templateListActionPerformed(evt);
            }
        });
        read_variables_Button.setText("读取变量");
        read_variables_Button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                read_variables_Button_action_Performed(evt);
            }
        });
        read_fields_from_table_Button.setText("从表读取字段");
        read_fields_from_table_Button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                read_fields_from_table_Button_ActionPerformed(evt);
            }
        });
        top_file_menu.setText("文件");
        top_file_open_MenuItem.setText("Open");
        top_file_menu.add(top_file_open_MenuItem);
        top_file_database_setter_menu_Item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        top_file_database_setter_menu_Item.setText("数据源设置");
        top_file_database_setter_menu_Item.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                top_file_database_setter_menu_Item_ActionPerformed(evt);
            }
        });
        top_file_menu.add(top_file_database_setter_menu_Item);
        model_path_setting_Item.setText("模板路径设置");
        top_file_menu.add(model_path_setting_Item);
        top_file_menu.add(jSeparator1);
        generate_path_setting_Item.setText("生成路径设置");
        top_file_menu.add(generate_path_setting_Item);
        generate_code_Item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        generate_code_Item.setText("生成代码");
        top_file_menu.add(generate_code_Item);
        top_file_menu.add(jSeparator2);
        exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        exitMenuItem.setText("退出");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        top_file_menu.add(exitMenuItem);
        menuBar.add(top_file_menu);
        editMenu.setText("编辑");
        cutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        cutMenuItem.setText("剪切");
        editMenu.add(cutMenuItem);
        copyMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        copyMenuItem.setText("复制");
        editMenu.add(copyMenuItem);
        pasteMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        pasteMenuItem.setText("\u7c98\u8d34");
        editMenu.add(pasteMenuItem);
        menuBar.add(editMenu);
        helpMenu.setText("帮助");
        contentsMenuItem.setText("关于");
        contentsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                contentsMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(contentsMenuItem);
        aboutMenuItem.setText("\u5e2e\u52a9");
        helpMenu.add(aboutMenuItem);
        menuBar.add(helpMenu);
        fileMenu1.setText("\u6587\u4ef6");
        openMenuItem1.setText("Open");
        fileMenu1.add(openMenuItem1);
        dataBaseItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        dataBaseItem1.setText("\u6570\u636e\u6e90\u8bbe\u7f6e");
        dataBaseItem1.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                top_file_database_setter_menu_Item_ActionPerformed(evt);
            }
        });
        fileMenu1.add(dataBaseItem1);
        modelPathItem1.setText("\u6a21\u677f\u8def\u5f84\u8bbe\u7f6e");
        fileMenu1.add(modelPathItem1);
        fileMenu1.add(jSeparator3);
        generatePathItem1.setText("\u751f\u6210\u8def\u5f84\u8bbe\u7f6e");
        fileMenu1.add(generatePathItem1);
        generateItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        generateItem1.setText("\u751f\u6210\u4ee3\u7801");
        fileMenu1.add(generateItem1);
        fileMenu1.add(jSeparator4);
        exitMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        exitMenuItem1.setText("\u9000\u51fa");
        exitMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu1.add(exitMenuItem1);
        menuBar1.add(fileMenu1);
        editMenu1.setText("\u7f16\u8f91");
        cutMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        cutMenuItem1.setText("\u526a\u5207");
        editMenu1.add(cutMenuItem1);
        copyMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        copyMenuItem1.setText("\u590d\u5236");
        editMenu1.add(copyMenuItem1);
        pasteMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        pasteMenuItem1.setText("\u7c98\u8d34");
        editMenu1.add(pasteMenuItem1);
        menuBar1.add(editMenu1);
        helpMenu1.setText("\u5e2e\u52a9");
        contentsMenuItem1.setText("\u5173\u4e8e");
        contentsMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                contentsMenuItemActionPerformed(evt);
            }
        });
        helpMenu1.add(contentsMenuItem1);
        aboutMenuItem1.setText("\u5e2e\u52a9");
        helpMenu1.add(aboutMenuItem1);
        menuBar1.add(helpMenu1);
        jButton1.setText("\u4eceModel\u8bfb\u53d6");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton2.setText("\u6dfb\u52a0\u5b57\u6bb5");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jButton4.setText("\u5220\u9664\u5b57\u6bb5");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jButton5.setText("\u751f\u6210\u524d\u53f0Model");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        fileMenu2.setText("\u6587\u4ef6");
        openMenuItem2.setText("Open");
        fileMenu2.add(openMenuItem2);
        dataBaseItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        dataBaseItem2.setText("\u6570\u636e\u6e90\u8bbe\u7f6e");
        dataBaseItem2.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                top_file_database_setter_menu_Item_ActionPerformed(evt);
            }
        });
        fileMenu2.add(dataBaseItem2);
        modelPathItem2.setText("模板路径设置");
        fileMenu2.add(modelPathItem2);
        fileMenu2.add(jSeparator5);
        generatePathItem2.setText("生成路径设置");
        fileMenu2.add(generatePathItem2);
        generateItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        generateItem2.setText("\u751f\u6210\u4ee3\u7801");
        fileMenu2.add(generateItem2);
        fileMenu2.add(jSeparator6);
        exitMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        exitMenuItem2.setText("\u9000\u51fa");
        exitMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu2.add(exitMenuItem2);
        menuBar2.add(fileMenu2);
        editMenu2.setText("\u7f16\u8f91");
        cutMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        cutMenuItem2.setText("\u526a\u5207");
        editMenu2.add(cutMenuItem2);
        copyMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        copyMenuItem2.setText("\u590d\u5236");
        editMenu2.add(copyMenuItem2);
        pasteMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        pasteMenuItem2.setText("\u7c98\u8d34");
        editMenu2.add(pasteMenuItem2);
        menuBar2.add(editMenu2);
        helpMenu2.setText("\u5e2e\u52a9");
        contentsMenuItem2.setText("\u5173\u4e8e");
        contentsMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                contentsMenuItemActionPerformed(evt);
            }
        });
        helpMenu2.add(contentsMenuItem2);
        aboutMenuItem2.setText("\u5e2e\u52a9");
        helpMenu2.add(aboutMenuItem2);
        menuBar2.add(helpMenu2);
        setJMenuBar(menuBar2);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addGroup(
                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGap(19, 19, 19)
                                                                .addGroup(
                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(model_root_path_jLabel9)
                                                                                .addGroup(
                                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(create_template_jLabel11)
                                                                                                .addComponent(create_root_path_jLabel10)))
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addGroup(
                                                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                                                                                .addComponent(templatePath, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                                                                                                                .addComponent(generatePath))
                                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                .addGroup(
                                                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                                .addComponent(changeTemplatePath).addComponent(changeGeneratePath)))
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addComponent(templateList, javax.swing.GroupLayout.PREFERRED_SIZE, 201,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                                                                .addComponent(read_variables_Button)
                                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                .addGroup(
                                                                                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                                .addGroup(
                                                                                                                        layout.createSequentialGroup().addComponent(read_fields_from_table_Button)
                                                                                                                                .addGap(10, 10, 10)
                                                                                                                                .addComponent(jButton2))
                                                                                                                .addGroup(
                                                                                                                        layout.createSequentialGroup()
                                                                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                                                .addComponent(jButton1).addGap(18, 18, 18).addComponent(jButton4))))))
                                                .addGroup(layout.createSequentialGroup().addGap(227, 227, 227).addComponent(create_code_jButton3).addGap(27, 27, 27).addComponent(jButton5))
                                                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(filed_config_jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 657,
                                                        Short.MAX_VALUE)))
                                .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(model_root_path_jLabel9)
                                        .addComponent(templatePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(changeTemplatePath))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(create_root_path_jLabel10)
                                        .addComponent(generatePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(changeGeneratePath))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(create_template_jLabel11)
                                        .addComponent(templateList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(read_variables_Button).addComponent(read_fields_from_table_Button).addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton1).addComponent(jButton4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(filed_config_jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(create_code_jButton3).addComponent(jButton5)).addContainerGap()));
        pack();
    }// </editor-fold>
    // GEN-END:initComponents

    /**
     * @Title: initHelpAbout
     * @Description: 初始化 “帮助-关于”信息
     * @Return void
     */
    private void initHelpAbout() {
        help_about.setMinimumSize(new java.awt.Dimension(300, 250));
        help_about.setModal(true);
        help_about.setResizable(false);
        help_about_jLabel6.setText("作者：符楚");
        help_about_jLabel7.setText("版本：V 1.0");
        help_about_jLabel8.setText("产品：代码生成器");
        javax.swing.GroupLayout aboutLayout = new javax.swing.GroupLayout(help_about.getContentPane());
        help_about.getContentPane().setLayout(aboutLayout);
        aboutLayout.setHorizontalGroup(aboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                aboutLayout.createSequentialGroup().addGap(106, 106, 106)
                        .addGroup(aboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(help_about_jLabel8).addComponent(help_about_jLabel6)
                                .addComponent(help_about_jLabel7))
                        .addContainerGap(155, Short.MAX_VALUE)));
        aboutLayout.setVerticalGroup(aboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                aboutLayout.createSequentialGroup().addGap(75, 75, 75).addComponent(help_about_jLabel8).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(help_about_jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(help_about_jLabel7).addContainerGap(130, Short.MAX_VALUE)));
        help_about.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - help_about.getWidth()) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - help_about.getHeight()) / 2);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("代码生成器");
    }

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        // String className =
        // CommonUtils.changeFirstUpper(CommonUtils.getProperty(tableName));
        // StringBuffer fieldCode = new StringBuffer();
        // StringBuffer getSetFunc = new StringBuffer();
        // Map<String, String> importPackage = new HashMap<String, String>();
        // StringBuffer code = new StringBuffer();
        // List<Field> fields = getFields();
        // fieldCode.append(" private static final long serialVersionUID =
        // 1L;\n");
        // for (Field field : fields) {
        // if (field.getFieldCName() != null &&
        // !"null".equals(field.getFieldCName()) &&
        // field.getFieldCName().trim().length() > 0) {
        // fieldCode.append(" /**\n");
        // fieldCode.append(" * " + field.getFieldCName() + "\n");
        // fieldCode.append(" */\n");
        // }
        // fieldCode.append(" @ColumnInfo(name = \"" + field.getTableField()
        // + "\")\n");
        // fieldCode.append(" private ").append(field.getFieldType()).append("
        // ").append(field.getFieldName()).append(";\n");
        // fieldCode.append("\n");
        // // getter
        // getSetFunc.append(" public ");
        // getSetFunc.append(field.getFieldType());
        // getSetFunc.append(" get");
        // getSetFunc.append(CommonUtils.changeFirstUpper(field.getFieldName()));
        // getSetFunc.append("(){\n return this.");
        // getSetFunc.append(field.getFieldName());
        // getSetFunc.append(";\n }\n\n");
        // // setter
        // getSetFunc.append(" public void set");
        // getSetFunc.append(CommonUtils.changeFirstUpper(field.getFieldName()));
        // getSetFunc.append("(");
        // getSetFunc.append(field.getFieldType());
        // getSetFunc.append(" ").append(field.getFieldName());
        // getSetFunc.append("){\n this.");
        // getSetFunc.append(field.getFieldName());
        // getSetFunc.append(" = ").append(field.getFieldName());
        // getSetFunc.append(";\n }\n\n");
        // if ("BigDecimal".equals(field.getFieldType())) {
        // importPackage.put("BigDecimal", "import java.math.BigDecimal;\n");
        // } else if ("Date".equals(field.getFieldType())) {
        // importPackage.put("Date", "import java.util.Date;\n");
        // }
        // }
        // code.append("package com.gd10086.portal.model.mall;\n");
        // code.append("\n");
        // code.append("import
        // com.jaf.platform.persistence.jdbc.annotations.ColumnInfo;\n");
        // code.append("import
        // com.jaf.platform.persistence.jdbc.annotations.EntityInfo;\n");
        // code.append("import
        // com.jaf.platform.persistence.jdbc.annotations.Operation;\n");
        // code.append("import
        // com.jaf.platform.persistence.jdbc.annotations.Operations;\n");
        // code.append("\n");
        // for (String str : importPackage.values())
        // code.append(str);
        // code.append("\n");
        // code.append("@EntityInfo(name = \"" + tableName + "\", schema = \"" +
        // schema + "\")\n");
        // code.append("@Operations({\n");
        // code.append(" @Operation(name=\"get" + className +
        // "\", sql=\"SELECT * FROM $tableName WHERE SID = ? with ur\")\n");
        // code.append("})\n");
        // code.append("public class " + className +
        // " extends MallBaseModel {\n");
        // code.append("\n");
        // code.append(fieldCode);
        // code.append("\n");
        // code.append(" public " + className + "() {\n }\n");
        // code.append("\n");
        // code.append(getSetFunc);
        // code.append("\n");
        // code.append("}\n");
        // FileOutputStream fos;
        // String filePath = this.generatePath.getText() + "\\" + className +
        // ".java";
        // try {
        // File f = new File(filePath);
        // if (!f.getParentFile().exists()) {
        // f.getParentFile().mkdirs();
        // }
        // if (!f.exists()) {
        // f.createNewFile();
        // }
        // fos = new FileOutputStream(f);
        // Writer out = new OutputStreamWriter(fos, "GBK");
        // out.write(code.toString());
        // out.close();
        // fos.close();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // JOptionPane.showMessageDialog(null, "文件生成成功，请检查文件：" + filePath + "！",
        // "成功",
        // JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * @param @return
     * @return List<Field> @throws
     * @Title: getFields @Description: 从界面中获取 Fields 列表 @Algorithm: Algorithm
     * Explanation<br>
     */
    private List<Field> getFields() {
        List<Field> fields = new ArrayList<Field>();
        DefaultTableModel fieldDtm = (DefaultTableModel) fieldTable.getModel();
        for (int i = 0; i < fieldDtm.getRowCount(); i++) {
            Field field = new Field();
            field.setTableField(String.valueOf(fieldDtm.getValueAt(i, 1)));
            field.setDataType(String.valueOf(fieldDtm.getValueAt(i, 2)));
            field.setFieldName(String.valueOf(fieldDtm.getValueAt(i, 3)));
            field.setFieldCName(String.valueOf(fieldDtm.getValueAt(i, 4)));
            field.setRemark(String.valueOf(fieldDtm.getValueAt(i, 4)));
            field.setFieldType(fieldDtm.getValueAt(i, 5));
            field.setLength(getInteger(fieldDtm.getValueAt(i, 6)));
            Object inputType = fieldDtm.getValueAt(i, 7);
            if (inputType != null && inputType instanceof ControlType) {
                field.setInputType((ControlType) inputType);
            }
            field.setWhetherQuery(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 8))));
            field.setWhetherList(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 9))));
            field.setWhetherEdit(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 10))));
            field.setWhetherPrimaryKey(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 11))));
            field.setWhetherRequest(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 12))));
            field.setUnique(Boolean.valueOf(String.valueOf(fieldDtm.getValueAt(i, 13))));
            if ("auditState".equalsIgnoreCase(field.getFieldName())) {
                field.setFieldType("AuditState");
            }
            fields.add(field);
        }
        return fields;
    }

    private void templateListActionPerformed(java.awt.event.ActionEvent evt) {
        this.filed_config_jTabbedPane1.setSelectedIndex(0);
        readVariables();
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        fieldManager.deleteSelected();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        this.filed_config_jTabbedPane1.setSelectedIndex(1);
        fieldManager.addRow(new Object[]{null});
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jfc.setFileSelectionMode(0);
        jfc.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isDirectory() || f.getName().endsWith(".java"));
            }

            @Override
            public String getDescription() {
                return "模型文件(*.java)";
            }
        });
        int state = jfc.showOpenDialog(null);
        if (state == 1) {
            return;
        } else {
            File f = jfc.getSelectedFile();
            this.generatePath.setText(f.getAbsolutePath());
            saveConfigFile(null);
        }
    }

    /**
     * @param evt
     * @Title: read_fields_from_table_Button_ActionPerformed
     * @Description: 按扭：“从表中读取字段”的操作
     * @Return void
     */
    private void read_fields_from_table_Button_ActionPerformed(java.awt.event.ActionEvent evt) {
        this.filed_config_jTabbedPane1.setSelectedIndex(1);
        String tempTableName = variablesTableValue("@{表名}");
        if (tempTableName != null && tempTableName.length() > 0) {
            tableName = tempTableName;
        } else {
            tableName = JOptionPane.showInputDialog("变量中没有找到表名的变量，请输入表名，如(commodity)：", tableName);
        }
        if (tableName != null && tableName.length() > 0) {
            this.fieldManager.clear();
            int database_type_selectedIndex = database_type_combo_box.getSelectedIndex();
            String databaseDriver = database_driver_text_field.getText().trim();
            String databaseUrl = database_url_text_field.getText().trim();
            String databaseUsername = database_username_text_field.getText().trim();
            String databasePassword = database_password_text_field.getText().trim();
            String databaseSchema = database_schema_text_field.getText().trim();

            if (isEmpty("数据源尚未设置", databaseDriver, databaseUrl, databaseUsername, databasePassword, databaseSchema)) {
                this.data_source_setter_dialog_window.setVisible(true);
                return;
            }

            String sql = getQueryFieldsSQL(database_type_selectedIndex, databaseSchema, tableName);

            System.out.printf("Query fields sql : %s %n", sql);

            ConnectionUtil util = new ConnectionUtil(databaseDriver, databaseUrl, databaseUsername, databasePassword);


            // 获取数据表字段信息
            List<Map<String, Object>> resultList = null;
            try {
                resultList = util.executeQuery(sql);

                if (resultList.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "读取字段信息为空, 请检查表名是否正确！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

            } catch (Exception e) {
                return;
            }
            TableManager manager = new TableManager(fieldTable);
            for (Map<String, Object> temp : resultList) {
                System.out.println(String.format("temp[%s]", JSON.toJSONString(temp)));
                Field field = this.getField(database_type_selectedIndex, temp);

                System.out.println(String.format("field[%s]", field));
                manager.addRow(new Object[]{null, field.getTableField(), field.getDataType().toUpperCase(), field.getFieldName(), field.getRemark(), field.getFieldType(), field.getLength(),
                        field.getInputType(),
                        field.isWhetherQuery(), field.isWhetherList(), field.isWhetherEdit(), field.isWhetherPrimaryKey(), field.isWhetherRequest(), field.isUnique()});
            }
        }
    }


    private boolean assertTrue(boolean expression, String message) {
        if (!expression) {
            JOptionPane.showMessageDialog(null, message, "错误", JOptionPane.ERROR_MESSAGE);
            return true;
        }
        return false;
    }

    private boolean isEmpty(String message, String... data) {
        for (String str : data) {
            if (str == null || str.length() == 0) {
                JOptionPane.showMessageDialog(null, message, "错误", JOptionPane.ERROR_MESSAGE);
                return true;
            }
        }
        return false;
    }

    private String variablesTableValue(String searchKey) {
        DefaultTableModel dtm = (DefaultTableModel) variablesTable.getModel();
        for (int i = 0; i < dtm.getRowCount(); i++) {
            String key = String.valueOf(dtm.getValueAt(i, 1));
            String value = dtm.getValueAt(i, 2) == null ? "" : String.valueOf(dtm.getValueAt(i, 2));
            if (key.equalsIgnoreCase(searchKey)) {
                return value;
            }
        }
        return null;
    }

    private Field getField(final int database_type_selectedIndex, final Map<String, Object> temp) {

        if (database_type_selectedIndex == DATABASE_TYPE_MYSQL) {
            return new MysqlField(temp);
        }

        if (database_type_selectedIndex == DATABASE_TYPE_SQL_SERVER) {
            // 处理每个字段的相关信息，放在 Field 对象中
            return new SqlServerField(temp);
        }

        return new Field(temp);
    }

    /**
     * @param database_type_selectedIndex 选择的数据库类型
     * @param tableName2
     * @param schema2
     * @return
     * @Title: getQueryFieldsSQL
     * @Description: 获取查询字段信息的SQL语句，根据不同的数据库类型
     * @Return String
     */
    private String getQueryFieldsSQL(int database_type_selectedIndex, String schema2, String tableName2) {
        String sql;
        if (database_type_selectedIndex == DATABASE_TYPE_MYSQL) {// mySql

            sql = String.format(
                    "select TABLE_SCHEMA AS TBCREATOR,TABLE_NAME AS TBNAME,COLUMN_NAME as NAME,IS_NULLABLE AS NULLS,DATA_TYPE AS COLTYPE,CHARACTER_MAXIMUM_LENGTH AS LENGTH,COLUMN_COMMENT AS REMARKS,COLUMN_KEY from information_schema.columns t where table_name='%s' and table_schema = '%s'",
                    tableName2, schema2);

        } else if (database_type_selectedIndex == DATABASE_TYPE_ORACLE) {// oracle
            sql = "select t.column_name as NAME,t.TABLE_NAME AS TBNAME,'"
                    + schema2
                    + "' as TBCREATOR,c.COMMENTS AS REMARKS,t.DATA_TYPE as COLTYPE,t.NULLABLE AS NULLS, t.DATA_LENGTH AS LENGTH,(SELECT '1' FROM user_cons_columns cu, user_constraints au where cu.constraint_name = au.constraint_name and au.constraint_type = 'P' AND au.table_name = t.table_name and cu.column_name=t.column_name) as KEYSEQ from user_tab_columns t,user_col_comments c where t.table_name = c.table_name and t.column_name = c.column_name and t.table_name = '"
                    + tableName2 + "'";
        } else if (database_type_selectedIndex == DATABASE_TYPE_SQL_SERVER) {
            sql = "select * from information_schema.columns t where table_name='" + tableName2 + "'";
        } else if (database_type_selectedIndex == DATABASE_TYPE_DB2) {
            sql = "select NAME,TBNAME,TBCREATOR,REMARKS,COLTYPE,NULLS,LENGTH,KEYSEQ from sysibm.syscolumns where TBNAME='" + tableName2 + "' AND tbCREATOR='" + schema2 + "' order by colno";
        } else {
            throw new RuntimeException("unknow database type!");
        }
        return sql;
    }

    private void read_variables_Button_action_Performed(java.awt.event.ActionEvent evt) {
        this.filed_config_jTabbedPane1.setSelectedIndex(0);
        readVariables();
    }

    private void changeGeneratePathActionPerformed(java.awt.event.ActionEvent evt) {
        jfc.setFileSelectionMode(1);
        jfc.setFileFilter(null);
        if (this.generatePath.getText().length() > 0) {
            jfc.setCurrentDirectory(new File(this.generatePath.getText()));
        }
        int state = jfc.showOpenDialog(null);
        if (state == 1) {
            return;
        } else {
            File f = jfc.getSelectedFile();
            this.generatePath.setText(f.getAbsolutePath());
            saveConfigFile(null);
        }
    }

    private void changeTemplatePathActionPerformed(java.awt.event.ActionEvent evt) {
        jfc.setFileSelectionMode(1);
        jfc.setFileFilter(null);
        if (this.templatePath.getText().length() > 0) {
            jfc.setCurrentDirectory(new File(this.templatePath.getText()));
        }
        int state = jfc.showOpenDialog(null);
        if (state == 1) {
            return;
        } else {
            File f = jfc.getSelectedFile();
            this.templatePath.setText(f.getAbsolutePath());
            this.templateList.setModel(initTemplateList());
            saveConfigFile(null);
        }
    }

    /**
     * 生成代码按扭
     *
     * @param evt
     * @example <调用范例>
     */
    private void create_code_jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        if (this.templatePath.getText().length() == 0 || this.generatePath.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "模板路径根路径和生成文件根路径不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        MyFile templateFile = (MyFile) this.templateList.getSelectedItem();
        if (templateFile == null || !templateFile.exists()) {
            JOptionPane.showMessageDialog(null, "模板文件夹不存在，请选择模板文件夹！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Map<String, String> variable = new HashMap<String, String>();
        variable.put("@{表名}", tableName);
        DefaultTableModel dtm = (DefaultTableModel) variablesTable.getModel();
        for (int i = 0; i < dtm.getRowCount(); i++) {
            String key = String.valueOf(dtm.getValueAt(i, 1));
            String value = dtm.getValueAt(i, 2) == null ? "" : String.valueOf(dtm.getValueAt(i, 2));
            String varia = CommonUtils.getVariable(key);
            variable.put(key, value);
            if (value == null || value.length() == 0) {
                JOptionPane.showMessageDialog(null, key + " 变量值不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            variable.put("@{" + varia + "_FIRST_LOWER}", CommonUtils.changeFirstLower(value));
            variable.put("@{" + varia + "_FIRST_UPPER}", CommonUtils.changeFirstUpper(value));
            variable.put("@{" + varia + "_LOWER}", value.toLowerCase(Locale.ENGLISH));
            variable.put("@{" + varia + "_LOWER_SPLIT}", CommonUtils.changeSplit(value));
        }
        List<Field> fields = getFields();
        for (Field field : fields) {
            System.out.println(field.toString());
        }
        Properties prop = new Properties();
        prop.putAll(variable);
        this.saveConfigFile(prop);

        CoastCodeGenerator ccg = new CoastCodeGenerator();
        ccg.setVariable(variable, fields);

        Generator gen = new Generator(templateFile.getAbsolutePath(), this.generatePath.getText(), variable, fields);
        gen.generator();
        JOptionPane.showMessageDialog(null, "文件生成成功，请检查生成路径！", "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    private Integer getInteger(Object value) {
        if (value == null || value.toString().length() == 0) {
            return 1;
        } else {
            return Integer.valueOf(value.toString().trim());
        }
    }

    private void contentsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        this.help_about.setVisible(true);
    }

    private void saveDataBaseActionPerformed(java.awt.event.ActionEvent evt) {
        this.data_source_setter_dialog_window.setVisible(false);
        saveConfigFile(null);
    }

    /**
     * @param evt
     * @Title: database_type_combo_box_ActionPerformed
     * @Description: 数据库类型选择框，选中时操作
     * @Return void
     */
    private void database_type_combo_box_ActionPerformed(java.awt.event.ActionEvent evt) {
        String selectDataBase = (String) this.database_type_combo_box.getSelectedItem();
        if ("DB2".equals(selectDataBase)) {
            this.database_driver_text_field.setText("com.ibm.db2.jcc.DB2Driver");
            this.database_url_text_field.setText("jdbc:db2://localhost:50000");
            this.database_username_text_field.setText("db2inst1");
            this.database_password_text_field.setText("db2inst1");
        } else if ("MYSQL".equals(selectDataBase)) {
            this.database_driver_text_field.setText("com.mysql.jdbc.Driver");
            this.database_url_text_field.setText("jdbc:mysql://localhost:3306/");
            this.database_username_text_field.setText("root");
        } else if ("ORACLE".equals(selectDataBase)) {
            this.database_driver_text_field.setText("oracle.jdbc.driver.OracleDriver");
            this.database_url_text_field.setText("jdbc:oracle:thin:@localhost:1521");
        }
    }

    /**
     * @param evt
     * @Title: top_file_database_setter_menu_Item_ActionPerformed
     * @Description: 菜单：“数据源设置”点击时的操作，弹出设置窗口
     * @Return void
     */
    private void top_file_database_setter_menu_Item_ActionPerformed(java.awt.event.ActionEvent evt) {
        this.data_source_setter_dialog_window.setVisible(true);
    }

    /**
     * @param evt
     * @Title: exitMenuItemActionPerformed
     * @Description: 退出按扭操作实现
     * @Return void
     */
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }// GEN-LAST:event_exitMenuItemActionPerformed

    /**
     * @return
     * @Title: initTemplateList
     * @Description: 初始化模板列表
     * @Return ComboBoxModel
     */
    private ComboBoxModel initTemplateList() {
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
        if (this.templatePath.getText().length() > 0) {
            File f = new File(this.templatePath.getText());
            if (f.exists()) {
                File[] list = f.listFiles(new java.io.FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() && !f.getName().contains(".svn");
                    }
                });
                if (list != null) {
                    for (int i = 0; i < list.length; i++) {
                        dcbm.addElement(new MyFile(list[i]));
                    }
                }
            }
        }
        return dcbm;
    }

    /**
     * 读取变量参数信息
     */
    private void readVariables() {
        MyFile f = (MyFile) this.templateList.getSelectedItem();
        Set<String> variables = new HashSet<String>();
        if (f != null) {
            variables.addAll(FileOperator.getAllVariables(f));
        }
        variableManager.clear();
        // 读取变量，并把变量信息增加到界面上展示
        Properties prop = this.loadConfigFile();
        for (String variable : variables) {
            System.out.println("variable:" + variable);

            if (this.doNotShowOnWindow(variable)) {
                continue;
            }

            variableManager.addRow(new Object[]{null, variable, prop.getProperty(variable)});
        }
    }

    /**
     * @param variable
     * @return
     * @Title: doNotShowOnWindow
     * @Description: 判断变量是否不显示在界面列表
     * @Return boolean
     */
    private boolean doNotShowOnWindow(String variable) {

        String[] notShowVariables = new String[]{"@{引入外部类}", "@{模型字段信息}",
                "@{搜索条件JAVA}", "@{搜索区}", "@{resultMap_info}",
                "@{data}",
                "@{Base_Column_List}",
                "@{update_set_column_selective}",
                "@{column_insert_values_list}",
                "@{insert_column_selective}",
                "@{insert_values_column_selective}",
                "@{domain_field_list}",
                "@{domain_vo_field_list}",
                "@{domain_dto_field_list}",
                "@{domain_update_dto_field_list}",
                "@{domain_save_dto_field_list}",
                "@{domain_query_dto_field_list}",
                "@{domain_field_list_set_get}",
                "@{dynamic_condition}", "@{domain_field_import_list}",
                "@{to_string}",
                "@{insert_batch_values}",
                //"@{js_init_column_list}",
                ///"@{html_search_column}",
                //"@{html_modal_edit}",

                //表格列表元素
                "@{vue_table_column_html}",

//编辑内容
                "@{vue_form_item_html}",

//下拉框初始化JS
                "@{vue_options_init_js}",

//下拉框导入到VUE
                "@{vue_options_init_js_import}",

//表单from元素声明
                "@{vue_form_item_js}",

//表单from规则声明
                "@{vue_form_rules_js}",

//过滤
                "@{vue_options_filters_js}"


        };

        for (String string : notShowVariables) {
            if (string.equals(variable)) {
                return true;
            }
        }

        if (variable.endsWith("_LOWER_SPLIT}") ||
                variable.endsWith("_LOWER}") ||
                variable.endsWith("_FIRST_UPPER}") ||
                variable.endsWith("_FIRST_LOWER}")) {
            return true;
        }

        return false;
    }

    /**
     * @Title: saveConfigFile
     * @Description: 保存配置路径
     * @Return void
     */
    private void saveConfigFile(Properties props) {
        String filePath = getConfigFilePath();

        Properties prop = new Properties();
        if (props != null) {
            prop.putAll(props);
        }

        if (isEmpty("数据源设置不完整", database_driver_text_field.getText().trim(),
                database_url_text_field.getText().trim(),
                database_username_text_field.getText().trim(),
                database_password_text_field.getText().trim(),
                database_schema_text_field.getText().trim()
        )) {
            this.data_source_setter_dialog_window.setVisible(true);
            return;
        }

        prop.put("templatePath", templatePath.getText().trim());
        prop.put("generatePath", generatePath.getText().trim());
        prop.put("dataBaseType", String.valueOf(database_type_combo_box.getSelectedIndex()));
        prop.put("dataDriver", database_driver_text_field.getText().trim());
        prop.put("dataUrl", database_url_text_field.getText().trim());
        prop.put("dataUserName", database_username_text_field.getText().trim());
        prop.put("dataPassword", database_password_text_field.getText().trim());
        prop.put("dataSchema", database_schema_text_field.getText().trim());
        File f = new File(filePath);
        try {
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStream os = new FileOutputStream(f);
            prop.store(new FileOutputStream(f), "配置文件");
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title: loadConfigFile
     * @Description: 加载配置文件
     * @Return void
     */
    private Properties loadConfigFile() {
        String filePath = getConfigFilePath();
        Properties prop = new Properties();
        File f = new File(filePath);
        if (f.exists()) {
            try {
                InputStream is = new FileInputStream(f);
                prop.load(is);
                is.close();
                templatePath.setText(prop.getProperty("templatePath"));
                generatePath.setText(prop.getProperty("generatePath"));
                String type = prop.getProperty("dataBaseType");
                if (type != null && type.length() > 0) {
                    database_type_combo_box.setSelectedIndex(Integer.valueOf(type.trim()).intValue());
                }
                database_driver_text_field.setText(prop.getProperty("dataDriver"));
                database_url_text_field.setText(prop.getProperty("dataUrl"));
                database_username_text_field.setText(prop.getProperty("dataUserName"));
                database_password_text_field.setText(prop.getProperty("dataPassword"));
                database_schema_text_field.setText(prop.getProperty("dataSchema"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return prop;
    }

    /**
     * @return
     * @Title: getConfigFilePath
     * @Description: 获取配置文件路径
     * @Return String
     */
    private String getConfigFilePath() {
        final String property = System.getProperty("file.separator");
        String filePath = MyPath.getProjectPath() + property + "config.ini";
        //filePath = this.handleConfigFilePath(filePath);
        System.out.printf("save config file path: %s %n", filePath);
        return filePath;
    }

    private String handleConfigFilePath(String filePath) {
        String[] directorys = filePath.split("\\\\");
        StringBuilder sb = new StringBuilder();
        for (String string : directorys) {
            string = string.trim();
            if (!string.equals("classes") && !string.equals("target") && !string.equals("test-classes")) {
                sb.append(string);
                if (!string.equals("config.ini")) {
                    sb.append("\\");
                }
            }
        }
        return sb.toString();
    }

    private void initTableColumn() {
        JComboBox jcmb = new JComboBox();
        for (FieldType type : FieldType.values()) {
            jcmb.addItem(type);
        }
        jcmb.setEditable(true);
        fieldManager.addEditor(5, new DefaultCellEditor(jcmb));
        JComboBox input = new JComboBox();
        for (ControlType type : ControlType.values()) {
            input.addItem(type);
        }
        input.setEditable(true);
        fieldManager.addEditor(7, new DefaultCellEditor(input));
        JCheckBox query = new JCheckBox();
        fieldManager.addEditor(8, new DefaultCellEditor(query));
        JCheckBox list = new JCheckBox();
        fieldManager.addEditor(9, new DefaultCellEditor(list));
        JCheckBox edit = new JCheckBox();
        fieldManager.addEditor(10, new DefaultCellEditor(edit));
        JCheckBox key = new JCheckBox();
        fieldManager.addEditor(11, new DefaultCellEditor(key));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CodeGenerator().setVisible(true);
            }
        });
    }

    // GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JDialog help_about;
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem aboutMenuItem1;
    private javax.swing.JMenuItem aboutMenuItem2;
    private javax.swing.JButton changeGeneratePath;
    private javax.swing.JButton changeTemplatePath;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenuItem contentsMenuItem1;
    private javax.swing.JMenuItem contentsMenuItem2;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem copyMenuItem1;
    private javax.swing.JMenuItem copyMenuItem2;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem cutMenuItem1;
    private javax.swing.JMenuItem cutMenuItem2;
    private javax.swing.JMenuItem top_file_database_setter_menu_Item;
    private javax.swing.JMenuItem dataBaseItem1;
    private javax.swing.JMenuItem dataBaseItem2;
    private javax.swing.JComboBox database_type_combo_box;
    private javax.swing.JTextField database_driver_text_field;
    private javax.swing.JTextField database_password_text_field;
    private javax.swing.JDialog data_source_setter_dialog_window;
    private javax.swing.JTextField database_url_text_field;
    private javax.swing.JTextField database_username_text_field;
    private javax.swing.JTextField database_schema_text_field;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenu editMenu1;
    private javax.swing.JMenu editMenu2;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenuItem exitMenuItem1;
    private javax.swing.JMenuItem exitMenuItem2;
    private javax.swing.JTable fieldTable;
    private TableManager fieldManager;
    private String tableName;
    private javax.swing.JMenu top_file_menu;
    private javax.swing.JMenu fileMenu1;
    private javax.swing.JMenu fileMenu2;
    private javax.swing.JMenuItem generate_code_Item;
    private javax.swing.JMenuItem generateItem1;
    private javax.swing.JMenuItem generateItem2;
    private javax.swing.JTextField generatePath;
    private javax.swing.JMenuItem generate_path_setting_Item;
    private javax.swing.JMenuItem generatePathItem1;
    private javax.swing.JMenuItem generatePathItem2;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenu helpMenu1;
    private javax.swing.JMenu helpMenu2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton create_code_jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel database_type_jLabel1;
    private javax.swing.JLabel create_root_path_jLabel10;
    private javax.swing.JLabel create_template_jLabel11;
    private javax.swing.JLabel database_driven_jLabel2;
    private javax.swing.JLabel database_url_jLabel3;
    private javax.swing.JLabel database_username_jLabel4;
    private javax.swing.JLabel database_password_jLabel5;
    private javax.swing.JLabel database_schema_jLabel6;
    private javax.swing.JLabel help_about_jLabel6;
    private javax.swing.JLabel help_about_jLabel7;
    private javax.swing.JLabel help_about_jLabel8;
    private javax.swing.JLabel model_root_path_jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane filed_config_jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator6;
    private javax.swing.JTabbedPane filed_config_jTabbedPane1;
    private javax.swing.JFileChooser jfc;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuBar menuBar1;
    private javax.swing.JMenuBar menuBar2;
    private javax.swing.JMenuItem model_path_setting_Item;
    private javax.swing.JMenuItem modelPathItem1;
    private javax.swing.JMenuItem modelPathItem2;
    private javax.swing.JMenuItem top_file_open_MenuItem;
    private javax.swing.JMenuItem openMenuItem1;
    private javax.swing.JMenuItem openMenuItem2;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem pasteMenuItem1;
    private javax.swing.JMenuItem pasteMenuItem2;
    private javax.swing.JButton read_fields_from_table_Button;
    private javax.swing.JButton read_variables_Button;
    private javax.swing.JButton reset_datebase_config;
    private javax.swing.JButton save_database_config_button;
    private javax.swing.JComboBox templateList;
    private javax.swing.JTextField templatePath;
    private javax.swing.JTable variablesTable;
    private TableManager variableManager;
    // End of variables declaration//GEN-END:variables
}
